import { Middleware } from 'koa'
import { Readable } from 'node:stream'
import { parseXml } from '~/libs/wx/xml'

const unparsed = Symbol.for('unparsed')

const readStringToEnd = (input: Readable, encoding: BufferEncoding = 'utf-8') =>
    new Promise<string>((resolve, reject) => {
        input.on('end', () => resolve(chunks.join(''))).on('error', reject)
        const chunks: string[] = []
        if (input.readableEncoding) {
            input.on('data', (chunk: string) => {
                chunks.push(chunk)
            })
        } else {
            input.on('data', (chunk: Buffer) => {
                chunks.push(chunk.toString(encoding))
            })
        }
    })

/**
 * 解析XML请求体的中间件
 */
export default function xmlBody(): Middleware {
    return async (ctx, next) => {
        const xml = await readStringToEnd(ctx.req)
        const body = parseXml(xml)
        Object.assign(body, { [unparsed]: xml })
        ctx.request.body = body
        return next()
    }
}
